<template>
  <view class="less-input">
    <input
      class="input"
      :class="props.disabled ? 'disabled' : ''"
      :placeholder-style="props.placeholderStyle"
      :placeholder="placeholder"
      :value="props.modelValue"
      @input="onInput"
      :type="type"
      confirm-type="search"
      @confirm="onConfirm"
      :disabled="props.disabled"
      :focus="props.focus"
      :maxlength="props.maxlength"
    />
    <view v-if="showClear && !props.hideClear" class="clear" @click="onClear">
      <icon type="clear" :size="12" />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { isNumber } from '@/util/is';
import { ref } from 'vue';
import { computed, nextTick } from 'vue';

const props = defineProps<{
  placeholder?: string;
  placeholderStyle?: string;
  modelValue?: string;
  type?: 'text' | 'number' | 'digit' | 'tel' | 'password';
  disabled?: boolean;
  focus?: boolean;
  hideClear?: boolean;
  clearConfrim?: boolean; //点击clear时触发提交
  maxlength?: number;
}>();

const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void;
  (event: 'confirm', value: string): void;
}>();

const showClear = computed(() => {
  if (isNumber(props.modelValue)) {
    return (props.modelValue as Number).toString().length > 0;
  }
  return (props.modelValue?.length ?? 0) > 0;
});

const onInput = (e) => {
  emit('update:modelValue', e.detail.value);
};

const onConfirm = (e) => {
  emit('confirm', e.detail.value);
};

const onClear = () => {
  if (props.disabled) {
    return;
  }
  emit('update:modelValue', '');

  if (props.clearConfrim) {
    nextTick(() => {
      emit('confirm', '');
    });
  }
};
</script>

<style lang="scss" scoped>
.less-input {
  display: flex;
  align-items: center;
  text-align: left;

  .input {
    width: 100%;
    height: 100%;
    font-size: 24rpx;
    color: #000000;

    &.disabled {
      pointer-events: none;
    }
  }

  .clear {
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
  }

  .pwdctrl {
    margin-right: 5px;
    image {
      width: 15px;
      height: 15px;
    }
  }
}
</style>
